const fs = require('fs');
const http = require('http');
const url = require('url');
const path = require('path');
const server = new http.Server();
const net = require('net');
const bean = require('./bean/bean')
server.listen(8000, function () {
    console.log('listen 8000');
});
server.on('request', function (request, response) {
    try {
        handle(request, response);
    } catch (e) {
        console.log(e);
    }
});
let socket = null;

function createSocket() {
    let socket = net.createConnection(8002, '127.0.0.1');
    socket.on('data', function (data) {
        console.log(data);
    })

    socket.on('error', function (e) {
        console.log(e);
    })
    return socket;
}

const handle = function (req, res) {
    let reqUrl = url.parse(req.url);
    if (reqUrl.pathname === '/static') {
        let mainDir = process.cwd();
        let toUnicode = reqUrl.query;
        if (isNaN(toUnicode)) {
            toUnicode = url.domainToUnicode(reqUrl.query);
        }
        if (toUnicode) {
            let filePath = path.join(mainDir, toUnicode);
            let readStream = fs.createReadStream(filePath);
            readStream.on('data', function (d) {
                res.writeHead(200, {
                    'Content-Type': 'application/octet-stream'
                })
                res.write(d);
            });
            readStream.on('error', function (e) {
                res.writeHead(404, {
                    'Content-Type': 'application/octet-stream'
                })
                res.end();
                console.log(e);
            })
            readStream.on('end', function () {
                res.end();
            });
            return
        } else {
            res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'})
            res.write(bean.responseBean(404, '没找到照片').toString());
            res.end();
        }

    }
    if (reqUrl.pathname === '/test') {
        res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});

        let urlWithStringQuery = url.parse(req.url);
        if (socket == null || !socket.connecting) {
            socket = createSocket();
        }
        if (urlWithStringQuery.query === '1') {
            socket.write("1a");
        } else {
            socket.write("8bbbbbbbb");

        }
    }
    if (reqUrl.pathname === '/api') {
        let s = req.toString();
        console.log(s);
        res.writeHead(200, {
            'Content-Type': 'application/json; charset=UTF-8'
        })
        res.end("123")
        return;
    }
    res.end("123");
};